package com.yc.cloud.common.oauth.wechat.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yc.cloud.common.oauth.wechat.dto.resp.AccessTokenResp;
import com.yc.cloud.common.oauth.wechat.dto.resp.GetTicketResp;
import lombok.val;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @title: 公众号工具类
 * @Author JackGu
 * @Date: 2022/10/22 16:17
 * @Version 1.0
 */
public class WxSubscriptionUtils {

    public static final String BASE_URL = "https://api.weixin.qq.com/cgi-bin";
    public static final String SUCCESS = "0";
    /***
     * description: 获取公众号AccessToken
     * @param
     * @return java.lang.String
     */
    public static String getAccessToken(String appid, String appKey) {

        // val appKey = "39b6e98d63858d6ef09fb2a78cc01214";
        val url = BASE_URL + "/token?grant_type=client_credential&appid=" + appid + "&secret=" + appKey;
        val result = HttpUtil.get(url);
        System.out.println("getAccessToken result \n" + result);
        val accessTokenResp = JSONUtil.toBean(result, AccessTokenResp.class);
        return accessTokenResp.getAccessToken();
    }

    /***
     * description: 获取临时票据
     * @param accessToken  访问令牌
     * @return java.lang.String
     */
    public static String getTicket(String accessToken) {
        val url = BASE_URL + "/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        val result = HttpUtil.get(url);
        val getTicketResp = JSONUtil.toBean(result, GetTicketResp.class);
        if (SUCCESS.equals(String.valueOf(getTicketResp.getErrcode()))) {
            return getTicketResp.getTicket();
        }
        return "";
    }

//


    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
      //  ret.put("appid", appid);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);

    }
}
